package com.example.demo.config;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.Msg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 类名：TokenInterceptor.java
 * 路径：com.example.demo.config.TokenInterceptor.java
 * 创建人：tanyp
 * 创建时间：2019/12/10 15:23
 * 功能：token验证拦截器
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
@Slf4j
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    public TokenInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");

        //检查是否有passtoken注释，有则跳过认证
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 请求头中获取token
        String token = request.getHeader("token");
        // GET请求获取userId
        String userId = request.getParameter("userId");

        // 获取GET请求的userId
        if (isJson(request) && (Objects.isNull(userId) || Objects.equals("", userId))) {
            String jsonParam = new RequestWrapper(request).getBodyString();
            JSONObject jsonObject = JSONObject.parseObject(jsonParam);
            userId = String.valueOf(jsonObject.get("userId"));
        }

        // 验证token是否正确
        if (!Objects.isNull(token) && !Objects.equals("", token)) {
            try {
                String userId_ = JWTUtil.getUserId(token);
                //判断token是否相等
                if (!Objects.isNull(userId_) && Objects.equals(userId, userId_)) {
                    return true;
                } else {
                    responseMsg(response, response.getWriter(), Msg.tokenError());
                    return false;
                }
            } catch (Exception e) {
                responseMsg(response, response.getWriter(), Msg.tokenError());
                return false;
            }
        } else {
            responseMsg(response, response.getWriter(), Msg.tokenError());
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    /**
     * 方法名：isJson
     * 功能：判断本次请求的数据类型是否为json
     * 创建人：tanyp
     * 创建时间：2019/12/10 15:23
     * 入参：
     * 出参：
     * 修改人：
     * 修改时间：
     * 修改备注：
     */
    private boolean isJson(HttpServletRequest request) {
        if (request.getContentType() != null && Objects.equals("POST", request.getMethod().toUpperCase())) {
            return request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE);
        }
        return false;
    }

    private void responseMsg(HttpServletResponse response, PrintWriter out, Msg msg) {
        response.setContentType("application/json; charset=utf-8");
        String json = JSONObject.toJSONString(msg);
        out.print(json);
        out.flush();
        out.close();
    }
}
